<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>考试防切屏</title>
  </head>
  <script>
    // 计时器
    class TimerVal {
      constructor() {
        this.outDate = 0;
        this.leaveNum = 0;
        // 上次离开时间 本次离开时间 共计
        this.lastLeaveTimer = 0;
        this.nowLeaveTimer = 0;
        this.allTotal = 0;
      }

      static getInstance() {
        if (!TimerVal.instance) {
          TimerVal.instance = new TimerVal();
        }
        return TimerVal.instance;
      }
      // 设置时间
      setTiemr() {
        this.outDate = new Date().getTime();
      }
      // 重新进入
      getOverTiemr() {
        if (!this.outDate) return;
        let inDate = new Date().getTime();
        this.leaveNum++;
        // 验证
        this.calculatingParameter(inDate);
        // this.validateTimer();
        this.validateLeaveNum(this.leaveNum);
      }

      // 计算时间区间
      calculatingParameter(inDate) {
        this.lastLeaveTimer = this.nowLeaveTimer;
        this.nowLeaveTimer = ((inDate - this.outDate) / 1000).toFixed(2);
        this.allTotal += parseFloat(this.nowLeaveTimer);
        Okeystimer.innerHTML = this.nowLeaveTimer;
        Lasttimer.innerHTML = this.lastLeaveTimer;
        DOM.innerHTML = this.leaveNum; // 次数
        Alltimer.innerHTML = this.allTotal;
      }

      // 判断离开时间是否合法
      validateTimer(timestamp) {}
      // 判断离开次数是否合法
      validateLeaveNum(num) {
        if (num > 6) {
          console.log("您已经切屏超过六次! 系统将进行自动交卷");
        }
      }
    }
  </script>
  <body>
    <div>您切屏了： <span id="okeys">0</span>次</div>
    <div>您本次切屏共用时：<span id="okeystimer">0</span>秒</div>
    <div>您上次切屏共用时：<span id="lasttimer">0</span>秒</div>
    <div>您一共离开了: <span id="alltimer">0</span>秒</div>
    <script>
      const DOM = document.getElementById("okeys");
      const Okeystimer = document.getElementById("okeystimer");
      const Lasttimer = document.getElementById("lasttimer");
      const Alltimer = document.getElementById("alltimer");
      const timeFun = TimerVal.getInstance();

      // 注册监听器 (监听 tabs 切换)
      document.addEventListener("visibilitychange", function () {
        // 隐藏逻辑
        if (document.visibilityState == "hidden") {
          // 重新计算时间
          timeFun.setTiemr();
        } else if (document.visibilityState == "visible") {
          // 计算离开时间
          timeFun.getOverTiemr();
        }
      });

      // 以上方法虽然可以判断是否存在tabs切换 但是无法判断窗口是否处于聚焦状态
      window.onfocus = function () {
        timeFun.getOverTiemr();
      };
      window.onblur = function () {
        // 重新计算时间
        timeFun.setTiemr();
        console.log("请注意，你切屏了！");
      };
    </script>
  </body>
</html>
